<template>
  <div class="admin-container">
    <div class="app-container">
      <el-card class="box-card">

        <!-- 页头 -->
        <div
          slot="header"
          class="clearfix"
        >
          <span>管理员管理</span>
          <div class="form">

            <div class="box-add">
              <el-button
                type="primary"
                @click="addAdminFn()"
              >添加管理员</el-button>
            </div>
          </div>
        </div>

        <!-- 筛选 -->
        <div class="screen">
          <el-form
            :rules="screenRules"
            inline
            :model="query"
            ref="screenForm"
          >
            <el-form-item
              label="权限"
              prop="permission"
            >
              <el-select
                filterable
                clearable
                v-model="query.permission"
                placeholder="请选择权限"
              >
                <el-option
                  v-for="item in permissionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="状态"
              prop="state"
            >
              <el-select
                filterable
                clearable
                v-model="query.state"
                placeholder="请选择权限"
              >
                <el-option
                  v-for="item in stateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="screenSubmitFn()"
              >筛选</el-button>
              <el-button @click="screenResetFn()">重置</el-button>
            </el-form-item>
          </el-form>

          <el-form
            :inline="true"
            :model="queryForm"
            ref='queryForm'
            :rules='queryRules'
            class="query-form"
          >
            <el-form-item
              prop="job_number"
              label="工号"
            >
              <el-input
                v-model.trim="queryForm.job_number"
                placeholder="请输入查找工号"
                @keyup.enter.native="getQueryFn()"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="getQueryFn()"
              >查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格组件 -->
        <div
          class="table"
          style="height:80%"
        >
          <el-table
            :data="adminList"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              min-width='50px'
            >
            </el-table-column>
            <el-table-column
              prop="job_number"
              label="工号"
              min-width='80px'
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              min-width='80px'
            >
            </el-table-column>
            <el-table-column
              prop="gender"
              label="性别"
              min-width='50px'
            >
            </el-table-column>
            <el-table-column
              prop="phone"
              label="手机号"
              min-width='120px'
            >
            </el-table-column>
            <el-table-column
              label="状态"
              min-width='50px'
            >
              <template v-slot="{row}">{{row.state?'锁定':'正常'}}</template>
            </el-table-column>
            <el-table-column
              prop="permission"
              label="权限"
              min-width='50px'
            >
              <template v-slot="{row}">{{row.permission?'高级':'普通'}}</template>
            </el-table-column>
            <el-table-column
              label="操作"
              width='190x'
              fixed='right'
            >
              <template v-slot="{row}">
                <el-button
                  circle
                  size="mini"
                  icon="el-icon-search"
                  @click="rowInfoFn(row)"
                ></el-button>
                <el-button
                  type="primary"
                  circle
                  icon="el-icon-edit"
                  size="mini"
                  @click="rowUpdateFn(row)"
                ></el-button>

                <span v-if="userInfo.id !== row.id">
                  <el-popconfirm
                    title="确定解锁该用户吗？"
                    @confirm="rowlockFn(row)"
                    v-if="row.state"
                  >
                    <el-button
                      type="info"
                      circle
                      icon="el-icon-key"
                      size="mini"
                      slot="reference"
                    ></el-button>
                  </el-popconfirm>

                  <el-popconfirm
                    title="确定锁定该管理员吗？"
                    @confirm="rowlockFn(row)"
                    v-else
                  >
                    <el-button
                      type="info"
                      circle
                      icon="el-icon-lock"
                      size="mini"
                      slot="reference"
                    >
                    </el-button>
                  </el-popconfirm>

                  <el-popconfirm
                    title="确定删除该管理员吗？"
                    @confirm="rowDeleteFn(row)"
                  >
                    <el-button
                      slot="reference"
                      type="danger"
                      circle
                      icon="el-icon-delete"
                      size="mini"
                    ></el-button>
                  </el-popconfirm>
                </span>

              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px; margin-top: 40px;"
          v-if="total > query.pagesize"
        >
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            hide-on-single-page
          />
        </el-row>

        <el-dialog
          title="管理员信息"
          :visible.sync="dialogInfoVisible"
          @close="dialogCloseFn()"
          :show-close='false'
          custom-class='dialog-info-35'
        >
          <el-descriptions
            border
            :column='2'
            labelClassName="width-100"
          >
            <el-descriptions-item
              label="id号"
              span="2"
            >{{adminInfo.id}}</el-descriptions-item>
            <el-descriptions-item label="工号">{{adminInfo.job_number}}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{adminInfo.name}}</el-descriptions-item>
            <el-descriptions-item label="性别">{{adminInfo.gender}}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{adminInfo.phone}}</el-descriptions-item>
            <el-descriptions-item label="状态">{{adminInfo.state? '锁定':'正常'}}</el-descriptions-item>
            <el-descriptions-item label="权限">{{adminInfo.permission? '高级':'普通'}}</el-descriptions-item>
          </el-descriptions>
        </el-dialog>

        <el-dialog
          :title="isAdd ? '添加管理员':'修改管理员信息'"
          :visible.sync="dialogUpdateVisible"
          @close="dialogCloseFn()"
          :close-on-click-modal='false'
          :show-close='false'
          custom-class='dialog-30'
        >
          <el-form
            :model="adminInfo"
            status-icon
            :rules="adminRules"
            ref="adminInfo"
            label-width="80px"
          >
            <el-form-item
              label="工号"
              prop="job_number"
            >
              <el-input
                v-model.trim="adminInfo.job_number"
                @keyup.enter.native="updateSubmitFn()"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="姓名"
              prop="name"
            >
              <el-input
                v-model.trim="adminInfo.name"
                @keyup.enter.native="updateSubmitFn()"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="密码"
              prop="password"
              v-if="isAdd"
            >
              <el-input
                type="password"
                v-model.trim="adminInfo.password"
                clearable
                minlength="6"
                maxlength="12"
                show-password
                @keyup.enter.native="updateSubmitFn()"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="性别"
              prop="gender"
            >
              <el-radio-group v-model="adminInfo.gender">
                <el-radio label="女"></el-radio>
                <el-radio label="男"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="phone"
            >
              <el-input
                v-model.trim="adminInfo.phone"
                @keyup.enter.native="updateSubmitFn()"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="权限"
              prop="permission"
            >
              <el-radio-group v-model="adminInfo.permission">
                <el-radio :label="0">普通</el-radio>
                <el-radio :label="1">高级</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item class="center">
              <el-button @click="dialogUpdateVisible = false">取消</el-button>
              <el-button
                type="primary"
                @click="updateSubmitFn()"
              >{{isAdd ? '添加':'修改'}}</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getAdminListAPI,
  queryAdminAPI,
  updateAdminAPI,
  lockAdminAPI,
  deleteAdminAPI,
  addAdminAPI
} from '@/api'
export default {
  name: 'adminList',
  computed: {
    ...mapGetters(['userInfo'])
  },
  data () {
    return {
      query: {
        page: 1, // 页码
        pagesize: 10, // 每页条数
        permission: '',
        state: ''
      }, // 获取列表数据
      adminList: [], // 管理员信息列表
      total: 0, // 总数
      queryForm: {
        job_number: ''
      }, // 查找数据
      queryRules: {
        job_number: [
          { required: true, message: '工号不能为空', trigger: 'blur' },
          {
            pattern: /^(gl)[0-9]{3,6}$/,
            message: '工号要求gl + 3-6个数字',
            trigger: 'blur'
          }
        ]
      }, // 查找数据验证
      dialogInfoVisible: false, // 信息展示 dialog 控制
      dialogUpdateVisible: false, // 修改信息 dialog 控制
      adminInfo: {
        gender: '男',
        permission: 0
      }, // dialog 数据
      adminRules: {
        password: [
          { required: true, message: '密码不能为空！', trigger: 'change' },
          {
            min: 6,
            max: 12,
            type: 'string',
            message: '密码要求6-12个字符',
            trigger: 'change'
          }
        ],
        phone: [
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ],
        id: [
          { required: true, message: 'id不能为空', trigger: 'blur' },
          {
            length: '32',
            type: 'string',
            message: 'id格式有误',
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            type: 'string',
            message: '姓名要求2-20个字符',
            trigger: 'blur'
          }
        ],
        job_number: [
          { required: true, message: '工号不能为空', trigger: 'blur' },
          {
            pattern: /^(gl)?[0-9]{3,6}$/,
            message: '工号要求3-6个数字',
            trigger: 'blur'
          }
        ],
        gender: [
          { required: true, message: '性别不能为空', trigger: 'blur' },
          {
            pattern: /^[男|女]$/,
            message: '性别格式有误',
            trigger: 'blur'
          }
        ],
        state: [
          { required: true, message: '状态不能为空', trigger: 'blur' },
          {
            pattern: /^[0|1]$/,
            message: '状态格式有误',
            trigger: 'blur'
          }
        ],
        permission: [
          { required: true, message: '权限不能为空', trigger: 'blur' },
          {
            pattern: /^[0|1]$/,
            message: '权限格式有误',
            trigger: 'blur'
          }
        ]
      }, // dialog 数据验证
      permissionOptions: [
        {
          value: 0,
          label: '普通'
        },
        {
          value: 1,
          label: '高级'
        }
      ], // 筛选权限数据
      screenRules: {
        state: [
          {
            pattern: /^[0|1]$/,
            message: '状态格式有误',
            trigger: 'blur'
          }
        ],
        permission: [
          {
            pattern: /^[0|1]$/,
            message: '权限格式有误',
            trigger: 'blur'
          }
        ]
      }, // 筛选数据验证
      stateOptions: [
        {
          value: 0,
          label: '正常'
        },
        {
          value: 1,
          label: '锁定'
        }
      ], // 筛选状态数据
      isAdd: false // 是否是添加操作
    }
  },
  created () {
    this.getAdminListFn()
  },
  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.size = newSize
      this.getAdminListFn() // 获取管理员列表
    },
    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getAdminListFn() // 获取管理员列表
    },
    // 获取管理员列表 -> 发送请求
    async getAdminListFn () {
      try {
        const { success, code, data } = await getAdminListAPI(this.query)
        if (success && code === 10000) {
          this.adminList = data.row
          this.total = data.total
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 根据输入工号查询
    async getQueryFn () {
      this.$refs.queryForm.validate(async (valid) => {
        if (valid) {
          try {
            const { success, code, data } = await queryAdminAPI(this.queryForm)
            if (success && code === 10000) {
              this.adminList = [data]
            }
          } catch (err) {
            return console.dir(err)
          }
        }
      })
    },
    // 点击查看 -> 展示数据详情
    rowInfoFn (row) {
      this.adminInfo = row
      this.dialogInfoVisible = true
    },
    // 点击修改 -> 展示数据 -> 修改
    rowUpdateFn (row) {
      this.adminInfo = { ...row }
      this.isAdd = false
      this.dialogUpdateVisible = true
    },
    // 点击锁定 -> 锁定管理员
    async rowlockFn (row) {
      try {
        const { success, code } = await lockAdminAPI({
          id: row.id,
          idLock: !!row.state
        })
        if (success && code === 10000) {
          row.state = row.state ? 0 : 1
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // 点击删除 -> 删除该管理员
    async rowDeleteFn (row) {
      try {
        const { success, code } = await deleteAdminAPI(row.id)
        if (success && code === 10000) {
          this.getAdminListFn()
        }
      } catch (err) {
        return console.dir(err)
      }
    },
    // dialog 关闭
    dialogCloseFn () {
      this.adminInfo = this.$options.data().adminInfo
      this.$refs.adminInfo?.resetFields()
    },
    // dialog 点击添加/修改 -> 发起请求
    updateSubmitFn () {
      this.$refs.adminInfo.validate(async (valid) => {
        if (valid) {
          try {
            delete this.adminInfo.state
            let success, code
            const jobNumber =
              this.adminInfo.job_number.indexOf('gl') > -1
                ? this.adminInfo.job_number
                : 'gl' + this.adminInfo.job_number
            if (this.isAdd) {
              ; ({ success, code } = await addAdminAPI({
                ...this.adminInfo,
                job_number: jobNumber
              }))
            } else {
              ; ({ success, code } = await updateAdminAPI({
                ...this.adminInfo,
                job_number: jobNumber
              }))
            }

            if (success && code === 10000) {
              this.getAdminListFn()
              this.dialogUpdateVisible = false
            }
          } catch (err) {
            return console.dir(err)
          }
        }
      })
    },
    // 点击筛选按钮 -> 重新获取列表
    screenSubmitFn () {
      this.$refs.screenForm.validate(async (valid) => {
        valid && this.getAdminListFn()
      })
    },
    // 清空筛选数据 -> 重新获取列表
    screenResetFn () {
      this.query = this.$options.data().query
      this.$refs.screenForm?.resetFields()
      this.getAdminListFn()
    },
    // 点击添加按钮
    addAdminFn () {
      this.isAdd = true
      this.dialogUpdateVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
</style>
